package com.kinptm.masterclock.adapter.item;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.kinptm.masterclock.R;
import com.kinptm.masterclock.adapter.ViewBuilder;
import com.kinptm.masterclock.bean.AlarmClock;
import com.kinptm.masterclock.db.DbHelper;
import com.kinptm.masterclock.utils.AlarmUtil;
import com.kinptm.masterclock.utils.ViewUtil;

import org.joda.time.DateTime;

import java.util.TreeSet;

/**
 * Created by pc on 13-11-13.
 */
public class AlarmClockItemBuilder extends ViewBuilder<AlarmClock> implements CompoundButton.OnCheckedChangeListener {

    @Override
    public View createView(LayoutInflater inflater, int position, AlarmClock data) {
        View view = inflater.inflate(R.layout.list_item_alarm_clock, null);
        updateView(view, position, data);
        return view;
    }

    @Override
    public void updateView(View view, int position, AlarmClock data) {
        super.updateView(view, position, data);
        CheckBox checkBox = ViewUtil.findView(view, R.id.alarm_clock_enable_cb);
        checkBox.setOnCheckedChangeListener(null);
        checkBox.setChecked(data.isEnable());
        checkBox.setTag(data);
        checkBox.setOnCheckedChangeListener(this);


        DateTime time = new DateTime(data.getAlarmMillis());
        ViewUtil.findTextViewAndSetText(view, R.id.alarm_clock_time_tv, time.toString("HH:mm"));


        CharSequence[] entries = view.getResources().getStringArray(R.array.weeks);

        TreeSet<Integer> values = data.getRepeat();

        StringBuilder result = new StringBuilder();
        if (values != null && values.size() > 0) {
            for (Integer value : values) {
                result.append(entries[value - 1]);
                result.append(",");
            }
            result.deleteCharAt(result.length() - 1);
        }
        TextView repeatTextView = ViewUtil.findView(view, R.id.alarm_clock_item_repeat_tv);
        ViewUtil.setGone(repeatTextView, result.length() == 0);
        ViewUtil.setText(repeatTextView, result.toString());
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        AlarmClock alarmClock = (AlarmClock) buttonView.getTag();

        alarmClock.setEnable(isChecked);

        DbHelper.getInstance().getAlarmClockDao().update(alarmClock);

        //ToastUtil.showLongTimeMsg(isChecked ? "启动闹钟" : "关闭闹钟");
        if (alarmClock.isEnable()) {
            AlarmUtil.nextAlarmClock(alarmClock);
            AlarmUtil.showIntervalTime(alarmClock);
            AlarmUtil.plan2AlarmClock(alarmClock);
        } else {
            AlarmUtil.cancel2AlarmClock(alarmClock);
        }

    }
}
